package com.linkhub.oms.component.mp.util;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linkhub.oms.common.constant.ProjectConstant;
import com.linkhub.oms.common.response.PageDTO;
import com.linkhub.oms.common.util.QtStreamUtil;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;

/**
 * @Description: QtMybatisPlusUtil
 * @Author: echo
 * @Date: 2024/3/28 16:17
 * @Version: 1.0
 */
public class QtMybatisPlusUtil {

    /**
     * convert 分页对象
     *
     * @param recordPage      recordPage
     * @param objectConverter objectConverter
     * @param <T>             entity
     * @param <R>             vo
     * @return pageDTO
     */
    public static <T, R> PageDTO<R> convertPage(Page<T> recordPage, Function<T, R> objectConverter) {
        if (ObjectUtil.isEmpty(recordPage)) {
            return null;
        }

        PageDTO<R> res = new PageDTO<>();
        res.setTotal(recordPage.getTotal());
        res.setSize(recordPage.getSize());
        res.setCurrent(recordPage.getCurrent());
        res.setPages(recordPage.getPages());
        res.setRecords(QtStreamUtil.map(recordPage.getRecords(), objectConverter));

        return res;
    }

    /**
     * 构建数组
     */
    @SuppressWarnings("all")
    public static <E> SFunction<E, ?>[] buildArray(SFunction<E, ?>... columns) {
        return Arrays.asList(columns).toArray(new SFunction[]{});
    }

    /**
     * 是否升序排序
     *
     * @param sortMode sortMode
     * @return true / false
     */
    public static boolean isAsc(String sortMode) {
        return Objects.equals(sortMode, ProjectConstant.ASCEND);
    }

    /**
     * 判断是否包含表字段的注解
     */
    public static boolean containColumnAnnotation(Field field) {
        return field.isAnnotationPresent(TableField.class) || field.isAnnotationPresent(TableId.class);
    }

    /**
     * 获取表字段名称
     */
    public static String getColumnName(Field field) {
        if (field == null) {
            return null;
        }

        return Optional
                .ofNullable(field.getAnnotation(TableId.class))
                .map(TableId::value)
                .orElseGet(() -> Optional
                        .ofNullable(field.getAnnotation(TableField.class))
                        .map(TableField::value)
                        .orElse(null));
    }
}
